<template>
  <div class="points-order-page">
    <!-- 商品信息 -->
    <div class="product-info">
      <div class="product-header">
        <img class="product-image" :src="product?.img" :alt="product?.title" />
        <div class="product-details">
          <h3 class="product-title">{{ product?.title }}</h3>
          <div class="price-info">
            <span class="current-price">¥{{ formatPrice(product?.price) }}</span>
            <span class="original-price" v-if="product?.discount_price">¥{{ formatPrice(product?.discount_price) }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 购买数量 -->
    <div class="quantity-section">
      <div class="section-title">购买数量</div>
      <div class="quantity-control">
        <span class="quantity-label">数量</span>
        <van-stepper v-model="count" min="1" max="99" @change="onQuantityChange" />
      </div>
    </div>

    <!-- 积分信息 -->
    <div class="points-section">
      <div class="section-title">积分支付</div>
      <div class="points-info">
        <div class="points-row">
          <span class="points-label">我的积分</span>
          <span class="points-value">{{ userPoints }}</span>
        </div>
        <div class="points-row">
          <span class="points-label">需要积分</span>
          <span class="points-value points-needed">{{ pointsNeeded }}</span>
        </div>
        <div v-if="pointsNeeded > userPoints" class="points-row">
          <span class="points-label">积分不足</span>
          <span class="points-value points-insufficient">还需 {{ pointsNeeded - userPoints }} 积分</span>
        </div>
      </div>
    </div>

    <!-- 订单总览 -->
    <div class="order-summary">
      <div class="section-title">订单总览</div>
      <div class="summary-item">
        <span class="summary-label">商品总价</span>
        <span class="summary-value">¥{{ formatPrice(totalPrice) }}</span>
      </div>
      <div class="summary-item">
        <span class="summary-label">积分抵扣</span>
        <span class="summary-value points-deduction">- ¥{{ formatPrice(pointsValue) }}</span>
      </div>
      <div class="summary-item summary-total">
        <span class="summary-label">实付金额</span>
        <span class="summary-value">¥{{ formatPrice(finalPrice) }}</span>
      </div>
    </div>

    <!-- 底部支付按钮 -->
    <div class="bottom-pay-container">
      <div class="pay-info">
        <span class="pay-label">积分支付</span>
        <span class="pay-value">{{ pointsNeeded }} 积分</span>
      </div>
      <van-button 
        type="primary" 
        size="large" 
        :disabled="!canPay"
        @click="onPointsPay"
        class="pay-btn"
      >
        {{ canPay ? '积分购买' : '积分不足' }}
      </van-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showToast, showLoadingToast, closeToast } from 'vant'
import { getSkusByIds } from '@/api/sku'
import { getUserInfo } from '@/api/user'
import { createPointsOrder } from '@/api/order'

const route = useRoute()
const router = useRouter()

// 响应式数据
const product = ref(null)
const count = ref(1)
const userPoints = ref(0)
const totalPrice = ref(0)
const pointsNeeded = ref(0)
const pointsValue = ref(0)
const finalPrice = ref(0)
const canPay = ref(false)

// 格式化价格
const formatPrice = (price) => {
  if (!price) return '0.00'
  return parseFloat(price).toFixed(2)
}

// 获取SKU信息
const getSkuInfo = async () => {
  try {
    const skuId = route.query.id
    const countValue = parseInt(route.query.count) || 1
    
    console.log('开始获取SKU信息')
    console.log('路由参数:', route.query)
    console.log('SKU ID:', skuId)
    console.log('数量:', countValue)
    
    if (!skuId) {
      console.error('SKU ID为空')
      showToast('商品ID不能为空')
      return
    }
    
    console.log('调用getSkusByIds API，参数:', skuId)
    
    // 调用SKU API获取商品信息
    const skus = await getSkusByIds(skuId)
    console.log('API响应:', skus)
    
    if (!skus || skus.length === 0) {
      console.error('SKU信息为空')
      showToast('商品信息不存在')
      return
    }
    
    product.value = skus[0]
    count.value = countValue
    
    console.log('设置商品信息:', product.value)
    console.log('设置数量:', count.value)
    
    // 计算价格
    calculatePrice()
  } catch (error) {
    console.error('获取SKU信息失败，详细错误:', error)
    console.error('错误类型:', error.name)
    console.error('错误消息:', error.message)
    if (error.response) {
      console.error('错误响应:', error.response)
    }
    showToast('获取商品信息失败: ' + error.message)
  }
}

// 获取用户积分
const getUserPoints = async () => {
  try {
    const userInfo = await getUserInfo()
    userPoints.value = userInfo.points || 0
    calculatePrice()
  } catch (error) {
    console.error('获取用户积分失败:', error)
    userPoints.value = 0
  }
}

// 数量变化
const onQuantityChange = (value) => {
  count.value = value
  calculatePrice()
}

// 计算价格和积分（与微信小程序保持一致）
const calculatePrice = () => {
  if (!product.value) return
  
  console.log('开始计算价格...')
  console.log('当前数据:', { product: product.value, count: count.value, userPoints: userPoints.value })
  
  const total = product.value.actual_price * count.value
  totalPrice.value = total
  
  // 假设1元=10积分，与微信小程序保持一致
  const needed = Math.floor(total * 10)
  pointsNeeded.value = needed
  
  const value = needed / 10
  pointsValue.value = value
  
  const final = total - value
  finalPrice.value = final > 0 ? final : 0
  
  canPay.value = userPoints.value >= needed
  
  console.log('计算结果:', {
    totalPrice: totalPrice.value,
    pointsNeeded: pointsNeeded.value,
    pointsValue: pointsValue.value,
    finalPrice: finalPrice.value,
    canPay: canPay.value
  })
}

// 积分购买
const onPointsPay = async () => {
  if (!canPay.value) {
    showToast('积分不足，无法购买')
    return
  }
  
  // 检查收款码状态
  const { checkQrcodeStatus } = await import('@/utils/qrcode-validator')
  const qrcodeValid = await checkQrcodeStatus(router.push)
  
  if (!qrcodeValid) {
    return // 收款码验证失败，已显示提示并跳转
  }
  
  showLoadingToast({
    message: '正在创建订单...',
    forbidClick: true,
  })
  
  try {
    // 构建订单数据
    const orderData = {
      total_price: totalPrice.value,
      final_total_price: finalPrice.value,
      points_to_pay: pointsNeeded.value,
      sku_info_list: [{
        id: product.value.id,
        count: count.value
      }],
      address: {
        // 这里可以添加地址信息
      }
    }
    
    console.log('提交订单数据:', orderData)
    
    // 调用积分购买API
    const orderId = await createPointsOrder(orderData)
    
    closeToast()
    showToast({
      type: 'success',
      message: '购买成功'
    })
    
    // 跳转到订单详情页
    setTimeout(() => {
      router.push({
        path: '/order-detail',
        query: { oid: orderId }
      })
    }, 1500)
    
  } catch (error) {
    closeToast()
    showToast({
      type: 'fail',
      message: error.message || '购买失败'
    })
  }
}

// 组件挂载时获取数据
onMounted(async () => {
  console.log('页面加载开始，参数:', route.query)
  
  // 检查收款码状态（页面级验证）
  const { quickCheckQrcode } = await import('@/utils/qrcode-validator')
  const qrcodeCheck = await quickCheckQrcode()
  
  if (!qrcodeCheck.valid) {
    // 收款码状态不满足要求，显示提示并跳转
    showToast(qrcodeCheck.message)
    
    // 延迟跳转，让用户看到提示
    setTimeout(() => {
      router.push('/my-qrcode')
    }, 1500)
    
    return // 阻止页面继续加载
  }
  
  // 收款码验证通过，继续加载页面
  // 获取SKU信息和用户积分
  await Promise.all([
    getSkuInfo(),
    getUserPoints()
  ])
})
</script>

<style lang="scss" scoped>
.points-order-page {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 100px;
}

.product-info {
  background: #fff;
  padding: 15px;
  margin-bottom: 10px;
  
  .product-header {
    display: flex;
    align-items: flex-start;
    
    .product-image {
      width: 80px;
      height: 80px;
      object-fit: cover;
      border-radius: 8px;
      margin-right: 15px;
    }
    
    .product-details {
      flex: 1;
      
      .product-title {
        font-size: 16px;
        color: #333;
        margin-bottom: 10px;
        line-height: 1.4;
      }
      
      .price-info {
        display: flex;
        align-items: center;
        
        .current-price {
          font-size: 18px;
          font-weight: bold;
          color: #9E2731;
          margin-right: 10px;
        }
        
        .original-price {
          font-size: 14px;
          color: #999;
          text-decoration: line-through;
        }
      }
    }
  }
}

.quantity-section {
  background: #fff;
  padding: 15px;
  margin-bottom: 10px;
  
  .section-title {
    font-size: 16px;
    color: #333;
    margin-bottom: 15px;
  }
  
  .quantity-control {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .quantity-label {
      font-size: 14px;
      color: #666;
    }
  }
}

.points-section {
  background: #fff;
  padding: 15px;
  margin-bottom: 10px;
  
  .section-title {
    font-size: 16px;
    color: #333;
    margin-bottom: 15px;
  }
  
  .points-info {
    .points-row {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10px;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .points-label {
        font-size: 14px;
        color: #666;
      }
      
      .points-value {
        font-size: 14px;
        color: #333;
        
        &.points-needed {
          color: #157658;
          font-weight: bold;
        }
        
        &.points-insufficient {
          color: #ff3b30;
        }
      }
    }
  }
}

.order-summary {
  background: #fff;
  padding: 15px;
  margin-bottom: 10px;
  
  .section-title {
    font-size: 16px;
    color: #333;
    margin-bottom: 15px;
  }
  
  .summary-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    &.summary-total {
      border-top: 1px solid #eee;
      padding-top: 10px;
      margin-top: 10px;
      
      .summary-label,
      .summary-value {
        font-size: 16px;
        font-weight: bold;
      }
    }
    
    .summary-label {
      font-size: 14px;
      color: #666;
    }
    
    .summary-value {
      font-size: 14px;
      color: #333;
      
      &.points-deduction {
        color: #9E2731;
      }
    }
  }
}

.bottom-pay-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  border-top: 1px solid #eee;
  padding: 15px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  
  .pay-info {
    .pay-label {
      display: block;
      font-size: 12px;
      color: #999;
      margin-bottom: 5px;
    }
    
    .pay-value {
      display: block;
      font-size: 16px;
      color: #157658;
      font-weight: bold;
    }
  }
  
  .pay-btn {
    width: 120px;
    height: 44px;
    background: #157658;
    border: none;
    
    &:disabled {
      background: #ccc;
    }
  }
}
</style> 